<template>
  <div class="chat-container">
    <!-- 语音通话覆盖层 -->
    <VoiceCallOverlay
      :visible="showVoiceOverlay"
      :agent-name="'Agent'"
      :is-agent-speaking="loading"
      :transcription-text="transcriptionText"
      :is-user-speaking="isUserSpeaking"
      :user-analyser="userAnalyser"
      :agent-analyser="agentAnalyser"
      :agent-response-text="agentResponseText"
      @minimize="handleVoiceMinimize"
      @close="handleVoiceClose"
      @toggle-mute="handleVoiceMute"
      @send-transcription="handleSendTranscription"
    />

    <!-- 语音通话最小化提示条 -->
    <div 
      v-if="ttsEnabled && !showVoiceOverlay" 
      class="voice-minimized-bar"
      @click="showVoiceOverlay = true"
    >
      <div class="bar-content">
        <el-icon class="pulse-icon"><Microphone /></el-icon>
        <span>语音通话进行中 · 点击返回通话界面</span>
      </div>
      <div class="bar-wave">
        <span></span><span></span><span></span><span></span>
      </div>
    </div>

    <!-- 头部 -->
    <div class="chat-header">
      <h1 class="text-xl font-semibold">Agent Chat</h1>
      <div class="header-actions">
        <!-- TTS控制按钮 -->
        <el-tooltip :content="ttsEnabled ? '关闭语音' : '开启语音'" placement="bottom">
          <el-button
            :type="ttsEnabled ? 'primary' : 'default'"
            :icon="ttsEnabled ? Microphone : Mute"
            circle
            @click="toggleTTS"
          />
        </el-tooltip>
        
        <!-- 音色选择 -->
        <el-select
          v-if="ttsEnabled"
          v-model="selectedVoice"
          placeholder="选择音色"
          size="small"
          style="width: 120px; margin-left: 10px"
        >
          <el-option label="芊悦" value="Cherry" />
          <el-option label="晨煦" value="Ethan" />
          <el-option label="不吃鱼" value="Nofish" />
          <el-option label="詹妮弗" value="Jennifer" />
          <el-option label="甜茶" value="Ryan" />
        </el-select>
        
        <el-button
          v-if="messages.length > 0"
          text
          @click="clearMessages"
          :icon="Delete"
          style="margin-left: 10px"
        >
          清空对话
        </el-button>
      </div>
    </div>

    <!-- 消息列表 -->
    <MessageList
      :messages="messages"
      :loading="loading"
      @restore="handleRestore"
      ref="messageListRef"
    />

    <!-- 输入区域 -->
    <InputArea
      ref="inputAreaRef"
      :loading="loading"
      :has-error="hasError"
      @send="handleSend"
      @retry="handleRetry"
      @pause="handlePause"
    />
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, watch, onBeforeUnmount } from 'vue'
import { Delete, Microphone, Mute, VideoPlay } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import MessageList from './MessageList.vue'
import InputArea from './InputArea.vue'
import VoiceCallOverlay from './VoiceCallOverlay.vue'
import { chatStream } from '../services/api'
import { MESSAGE_ROLE, MESSAGE_STATUS } from '../utils/constants'
import { 
  saveChatHistory, 
  loadChatHistory, 
  clearChatHistory,
  getCurrentSessionId,
  setCurrentSessionId
} from '../utils/storage'
import { getGlobalPlayer, destroyGlobalPlayer } from '../utils/audioPlayer'
import { ASRClient } from '../utils/asrClient'

const props = defineProps({
  sessionId: {
    type: String,
    default: null
  }
})

const messages = ref([])
const loading = ref(false)
const hasError = ref(false)
const messageListRef = ref(null)
const inputAreaRef = ref(null)
const currentSessionId = ref(getCurrentSessionId())
const currentCheckpointId = ref(null)
let abortController = null

// TTS相关状态
const ttsEnabled = ref(false)
const showVoiceOverlay = ref(false)
const selectedVoice = ref('Cherry')
const audioPlayer = ref(null)
const userAnalyser = ref(null)
const agentAnalyser = ref(null)

// ASR相关状态
const asrClient = ref(null)
const transcriptionText = ref('')
const isUserSpeaking = ref(false)
const agentResponseText = ref('')

// 处理语音通话相关事件
const handleVoiceMinimize = () => {
  showVoiceOverlay.value = false
}

const handleVoiceClose = () => {
  showVoiceOverlay.value = false
  if (ttsEnabled.value) {
    toggleTTS()
  }
  // 关闭ASR
  if (asrClient.value) {
    asrClient.value.close()
    asrClient.value = null
  }
}

const handleVoiceMute = async (isMuted) => {
  // 处理麦克风静音逻辑
  if (isMuted) {
    // 静音时停止录音
    if (asrClient.value) {
      asrClient.value.stopRecording()
      userAnalyser.value = null // 清空分析器，使波形停止
    }
  } else {
    // 取消静音时开始录音
    if (asrClient.value && asrClient.value.isConnected) {
      try {
        await asrClient.value.startRecording()
        userAnalyser.value = asrClient.value.getAnalyser()
      } catch (e) {
        console.error('[ASR] 重新开始录音失败:', e)
      }
    }
  }
}

// 发送识别的文本
const handleSendTranscription = (text) => {
  if (text && text.trim()) {
    handleSend(text.trim())
    transcriptionText.value = ''
    agentResponseText.value = '' // 清空AI回复，等待新的回复
  }
}

// 从本地存储加载聊天记录
const loadHistory = (sessionId = null) => {
  const targetSessionId = sessionId || props.sessionId || currentSessionId.value
  const history = loadChatHistory(targetSessionId)
  if (history && history.length > 0) {
    messages.value = history
    // 恢复后滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
  } else {
    messages.value = []
  }
}

// 保存聊天记录到本地存储（防抖）
let saveTimer = null
const saveHistory = () => {
  // 清除之前的定时器
  if (saveTimer) {
    clearTimeout(saveTimer)
  }
  // 延迟保存，避免频繁写入
  saveTimer = setTimeout(() => {
    const targetSessionId = props.sessionId || currentSessionId.value
    saveChatHistory(targetSessionId, messages.value)
  }, 500)
}

// 监听消息状态变化，自动保存
watch(
  () => messages.value.map(msg => `${msg.id}:${msg.status}`).join(','),
  () => {
    // 检查最后一条消息是否完成
    const lastMessage = messages.value[messages.value.length - 1]
    if (lastMessage && (lastMessage.status === MESSAGE_STATUS.COMPLETED || lastMessage.status === MESSAGE_STATUS.ERROR)) {
      saveHistory()
    }
  }
)

// 监听会话ID变化，切换会话
watch(
  () => props.sessionId,
  (newSessionId) => {
    if (newSessionId && newSessionId !== currentSessionId.value) {
      // 取消当前请求
      if (abortController) {
        abortController()
        abortController = null
      }
      // 保存当前会话
      saveHistory()
      // 切换会话
      currentSessionId.value = newSessionId
      setCurrentSessionId(newSessionId)
      // 重置 checkpoint ID，避免使用旧会话的 checkpoint
      currentCheckpointId.value = null
      // 加载新会话的历史记录
      loadHistory(newSessionId)
    }
  },
  { immediate: true }
)

// 组件挂载时加载历史记录
onMounted(() => {
  if (props.sessionId) {
    currentSessionId.value = props.sessionId
    setCurrentSessionId(props.sessionId)
  }
  loadHistory(props.sessionId)
  
  // 初始化音频播放器
  audioPlayer.value = getGlobalPlayer()
  agentAnalyser.value = audioPlayer.value.getAnalyser()
})

// 组件卸载时清理
onBeforeUnmount(() => {
  if (audioPlayer.value) {
    audioPlayer.value.stop()
  }
  if (asrClient.value) {
    asrClient.value.close()
  }
})

// 切换TTS开关
const toggleTTS = async () => {
  ttsEnabled.value = !ttsEnabled.value
  
  if (ttsEnabled.value) {
    showVoiceOverlay.value = true
    
    // 初始化ASR客户端
    try {
      asrClient.value = new ASRClient()
      
      await asrClient.value.connect(
        {
          language: 'zh',
          sampleRate: 16000,
          inputAudioFormat: 'pcm',
          enableTurnDetection: true
        },
        {
          onTranscription: (text, isComplete) => {
            if (isComplete) {
              // 完整识别结果
              transcriptionText.value = text
              console.log('[ASR] 完整识别:', text)
            } else {
              // 流式识别结果（部分）
              console.log('[ASR] 部分识别:', text)
            }
          },
          onSpeechStart: () => {
            isUserSpeaking.value = true
            console.log('[ASR] 用户开始说话')
          },
          onSpeechStop: () => {
            isUserSpeaking.value = false
            console.log('[ASR] 用户停止说话')
          },
          onError: (error) => {
            console.error('[ASR] 错误:', error)
            ElMessage.error(typeof error === 'string' ? error : '语音识别服务出错')
            ttsEnabled.value = false
            showVoiceOverlay.value = false
          },
          onConnected: async () => {
            console.log('[ASR] 连接成功')
            // 连接成功后开始录音
            try {
              await asrClient.value.startRecording()
              userAnalyser.value = asrClient.value.getAnalyser()
            } catch (e) {
              console.error('[ASR] 录音启动失败:', e)
              // 错误已在 onError 中处理，这里只需捕获避免未捕获异常
            }
          }
        }
      )
    } catch (error) {
      console.error('[ASR] 初始化失败:', error)
      ttsEnabled.value = false
      showVoiceOverlay.value = false
    }
  } else {
    showVoiceOverlay.value = false
    if (audioPlayer.value) {
      // 关闭TTS时停止播放
      audioPlayer.value.stop()
    }
    // 关闭ASR
    if (asrClient.value) {
      asrClient.value.close()
      asrClient.value = null
    }
  }
}

// 生成消息ID
const generateId = () => {
  return `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

// 发送消息
const handleSend = async (messageText) => {
  if (!messageText.trim() || loading.value) return

  // 添加用户消息
  const userMessage = {
    id: generateId(),
    role: MESSAGE_ROLE.USER,
    content: messageText,
    timestamp: Date.now(),
    status: MESSAGE_STATUS.COMPLETED
  }
  messages.value.push(userMessage)

  // 添加AI消息占位符
  const aiMessage = {
    id: generateId(),
    role: MESSAGE_ROLE.ASSISTANT,
    content: '',
    timestamp: Date.now(),
    status: MESSAGE_STATUS.STREAMING,
    items: [] // 按时间顺序的 items（工具调用和文本块）
  }
  messages.value.push(aiMessage)

  loading.value = true
  await nextTick()
  scrollToBottom()

  // 取消之前的请求
  if (abortController) {
    abortController()
  }

  // 获取会话ID
  const targetSessionId = props.sessionId || currentSessionId.value || getCurrentSessionId()
  
  // 准备历史记录：只包含已完成的消息，排除当前用户消息
  // 限制发送给后端的历史记录数量，避免请求过大（最多发送最近50条）
  const MAX_HISTORY_TO_SEND = 50
  const allHistory = messages.value
    .filter(msg => 
      msg.status === MESSAGE_STATUS.COMPLETED && 
      msg.id !== userMessage.id // 排除当前用户消息
    )
  
  // 只发送最近N条历史记录
  const history = allHistory.length > MAX_HISTORY_TO_SEND 
    ? allHistory.slice(-MAX_HISTORY_TO_SEND)
    : allHistory
  
  // 调用流式接口
  abortController = chatStream(
    messageText,
    // onMessage: 接收流式数据
    (content) => {
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage && lastMessage.role === MESSAGE_ROLE.ASSISTANT) {
        // 确保 items 数组存在
        if (!lastMessage.items) {
          lastMessage.items = []
        }
        
        // 查找最后一项
        const lastItem = lastMessage.items.length > 0 
          ? lastMessage.items[lastMessage.items.length - 1] 
          : null
        
        // 如果最后一项是文本块，追加到它；否则创建新的文本块
        if (lastItem && lastItem.type === 'text') {
          // 直接追加到最后一个文本块
          lastItem.content += content
        } else {
          // 创建新的文本块（这可能是因为前面有工具调用或这是第一条消息）
          const newTextItem = {
            type: 'text',
            content: content,
            id: `text_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
          }
          lastMessage.items.push(newTextItem)
        }
        
        // 同时更新 content 字段（用于兼容）
        lastMessage.content = lastMessage.items
          .filter(item => item.type === 'text')
          .map(item => item.content)
          .join('')
        
        // 更新语音通话界面显示的AI回复
        agentResponseText.value = lastMessage.content
        
        scrollToBottom()
      }
    },
    // onError: 错误处理
    (error) => {
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage && lastMessage.role === MESSAGE_ROLE.ASSISTANT) {
        lastMessage.status = MESSAGE_STATUS.ERROR
        lastMessage.error = error
        hasError.value = true
      }
      loading.value = false
      // 错误时也保存记录
      saveHistory()
    },
    // onComplete: 完成
    () => {
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage && lastMessage.role === MESSAGE_ROLE.ASSISTANT) {
        lastMessage.status = MESSAGE_STATUS.COMPLETED
      }
      loading.value = false
      hasError.value = false
      abortController = null
      
      // 完成后清除当前的 checkpoint_id，后续对话将自动基于最新的 thread state
      // 除非用户再次点击回滚
      currentCheckpointId.value = null
      
      // 消息完成后立即保存
      saveHistory()
      // AI输出完成后自动聚焦输入框，让用户可以直接输入
      nextTick(() => {
        if (inputAreaRef.value && typeof inputAreaRef.value.focus === 'function') {
          // 添加小延迟确保DOM完全更新
          setTimeout(() => {
            inputAreaRef.value.focus()
          }, 100)
        }
      })
    },
    // sessionId
    targetSessionId,
    // history: 传入所有已完成的消息作为历史记录
    history,
    // onToolCall: 处理工具调用
    (toolCallData) => {
      console.log('[前端] 收到工具调用事件:', toolCallData)
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage && lastMessage.role === MESSAGE_ROLE.ASSISTANT) {
        // 确保 items 数组存在
        if (!lastMessage.items) {
          lastMessage.items = []
        }
        
        if (toolCallData.type === 'start') {
          // 工具调用开始 - 添加到 items 数组
          const toolCallItem = {
            type: 'toolCall',
            id: toolCallData.tool_id,
            toolName: toolCallData.tool_name,
            toolArgs: toolCallData.tool_args,
            result: null,
            status: 'calling'
          }
          lastMessage.items.push(toolCallItem)
          console.log('[前端] 添加工具调用:', toolCallItem)
          scrollToBottom()
        } else if (toolCallData.type === 'result') {
          // 工具调用结果 - 更新对应的工具调用 item
          const resultToolId = String(toolCallData.tool_id || '')
          
          // 在 items 数组中查找对应的工具调用
          const toolCallItem = lastMessage.items.find(
            item => item.type === 'toolCall' && String(item.id) === resultToolId
          )
          
          if (toolCallItem) {
            toolCallItem.result = toolCallData.result
            toolCallItem.status = 'completed'
            console.log('[前端] 更新工具调用结果:', toolCallItem)
            scrollToBottom()
          } else {
            console.warn('[前端] 未找到匹配的工具调用，ID:', resultToolId)
            // 回退：更新最后一个工具调用
            const lastToolCallItem = [...lastMessage.items]
              .reverse()
              .find(item => item.type === 'toolCall' && item.status === 'calling')
            
            if (lastToolCallItem) {
              lastToolCallItem.result = toolCallData.result
              lastToolCallItem.status = 'completed'
              console.log('[前端] 回退：更新最后一个工具调用')
              scrollToBottom()
            }
          }
        }
      }
    },
    // onChart: 处理图表事件（新增）
    (chartData) => {
      console.log('[前端] 收到图表事件:', chartData)
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage && lastMessage.role === MESSAGE_ROLE.ASSISTANT) {
        // 确保 items 数组存在
        if (!lastMessage.items) {
          lastMessage.items = []
        }
        
        // 添加趋势图项
        const chartItem = {
          type: 'chart',
          chartType: chartData.type,
          chartData: chartData.data,
          id: `chart_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
        }
        lastMessage.items.push(chartItem)
        console.log('[前端] 添加趋势图:', chartItem)
        scrollToBottom()
      }
    },
    // onKnowledgeSearch: 处理知识库搜索事件（新增）
    (searchData) => {
      console.log('[前端] 收到知识库搜索事件:', searchData)
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage && lastMessage.role === MESSAGE_ROLE.ASSISTANT) {
        // 确保 items 数组存在
        if (!lastMessage.items) {
          lastMessage.items = []
        }
        
        // 添加知识库搜索结果项
        const searchResultItem = {
          type: 'knowledge_search',
          searchData: searchData.data,
          id: `search_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
        }
        lastMessage.items.push(searchResultItem)
        console.log('[前端] 添加知识库搜索结果:', searchResultItem)
        scrollToBottom()
      }
    },
    // onPlan: 处理任务计划事件（新增）
    (planData) => {
      console.log('[前端] 收到任务计划事件:', planData)
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage && lastMessage.role === MESSAGE_ROLE.ASSISTANT) {
        // 确保 items 数组存在
        if (!lastMessage.items) {
          lastMessage.items = []
        }
        
        // 每次都添加新的计划项
        const planItem = {
          type: 'plan',
          planData: planData.data,
          id: `plan_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
        }
        lastMessage.items.push(planItem)
        console.log('[前端] 添加/更新任务计划')
        scrollToBottom()
      }
    },
    // checkpointId: 如果有回滚，使用回滚点的ID
    currentCheckpointId.value,
    // onCheckpoint: 接收新的 checkpoint_id
    (checkpointData) => {
       console.log('[前端] 收到 Checkpoint:', checkpointData)
       const lastMessage = messages.value[messages.value.length - 1]
       if (lastMessage && lastMessage.role === MESSAGE_ROLE.ASSISTANT) {
         lastMessage.checkpointId = checkpointData.checkpoint_id
       }
    },
    // enableTTS: 是否启用TTS
    ttsEnabled.value,
    // onAudio: 接收音频数据
    (audioData, isDone = false) => {
      if (isDone) {
        console.log('[前端] 音频合成完成')
        return
      }
      
      if (audioData && audioPlayer.value) {
        // 添加音频到播放队列
        audioPlayer.value.addAudio(audioData)
      }
    },
    // voice: 选择的音色
    selectedVoice.value
  )
}

// 回滚到指定消息
const handleRestore = (message) => {
  if (!message || !message.id) return
  
  // 找到消息的索引
  const index = messages.value.findIndex(m => m.id === message.id)
  if (index === -1) return
  
  // 只有当消息有 checkpointId 时才能回滚
  if (!message.checkpointId) {
    console.warn('该消息没有 checkpointId，无法回滚')
    return
  }
  
  // 保留到当前消息，删除后面的消息
  messages.value = messages.value.slice(0, index + 1)
  
  // 设置下一次请求使用的 checkpointId
  currentCheckpointId.value = message.checkpointId
  
  // 保存变更
  saveHistory()
  
  // 聚焦输入框
  nextTick(() => {
    scrollToBottom()
    if (inputAreaRef.value && typeof inputAreaRef.value.focus === 'function') {
      inputAreaRef.value.focus()
    }
  })
}

// 重试最后一条消息
const handleRetry = () => {
  hasError.value = false
  const lastUserMessage = [...messages.value]
    .reverse()
    .find(msg => msg.role === MESSAGE_ROLE.USER)
  
  if (lastUserMessage) {
    // 移除最后一条AI消息（如果有错误）
    const lastMessage = messages.value[messages.value.length - 1]
    if (lastMessage && lastMessage.role === MESSAGE_ROLE.ASSISTANT) {
      messages.value.pop()
    }
    handleSend(lastUserMessage.content)
  }
}

// 暂停当前请求
const handlePause = () => {
  if (abortController) {
    abortController()
    abortController = null
    loading.value = false
    
    // 更新最后一条消息状态为已完成（暂停状态）
    const lastMessage = messages.value[messages.value.length - 1]
    if (lastMessage && lastMessage.role === MESSAGE_ROLE.ASSISTANT) {
      if (lastMessage.status === MESSAGE_STATUS.STREAMING) {
        lastMessage.status = MESSAGE_STATUS.COMPLETED
        // 保存当前状态
        saveHistory()
      }
    }
  }
}

// 清空消息
const clearMessages = () => {
  messages.value = []
  if (abortController) {
    abortController()
    abortController = null
  }
  loading.value = false
  hasError.value = false
  // 清空本地存储
  const targetSessionId = props.sessionId || currentSessionId.value
  clearChatHistory(targetSessionId)
}

// 滚动到底部
const scrollToBottom = () => {
  if (messageListRef.value) {
    messageListRef.value.scrollToBottom()
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  max-width: 1200px;
  margin: 0 auto;
  background: var(--el-bg-color);
  flex: 1;
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid var(--el-border-color-light);
  background: var(--el-bg-color);
  flex-shrink: 0;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.voice-minimized-bar {
  background: linear-gradient(90deg, #e6f7ff 0%, #f0f9ff 100%);
  color: #096dd9;
  padding: 8px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  border-bottom: 1px solid #bae7ff;
  transition: all 0.3s;
}

.voice-minimized-bar:hover {
  background: #bae7ff;
}

.bar-content {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
}

.pulse-icon {
  animation: pulse 1.5s infinite;
}

.bar-wave {
  display: flex;
  align-items: center;
  gap: 3px;
  height: 16px;
}

.bar-wave span {
  display: block;
  width: 3px;
  background-color: #1890ff;
  border-radius: 2px;
  animation: wave 1s infinite ease-in-out;
}

.bar-wave span:nth-child(1) { animation-delay: 0.0s; height: 6px; }
.bar-wave span:nth-child(2) { animation-delay: 0.1s; height: 10px; }
.bar-wave span:nth-child(3) { animation-delay: 0.2s; height: 8px; }
.bar-wave span:nth-child(4) { animation-delay: 0.3s; height: 5px; }

@keyframes pulse {
  0% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.1); opacity: 0.8; }
  100% { transform: scale(1); opacity: 1; }
}

@keyframes wave {
  0%, 100% { height: 4px; }
  50% { height: 12px; }
}

@media (max-width: 768px) {
  .chat-header {
    padding: 0.75rem 1rem;
  }
  
  .chat-header h1 {
    font-size: 1.125rem;
  }
}
</style>

